<template>
  <div class="mod-prod prod-list-mod">
    <div>
      <el-button
        type="text"
        icon="ArrowLeftBold"
        @click="onBack"
      >
        返回
      </el-button>
    </div>

    <div>
      <div style="display: flex">
        <div style="width: 120px; height: 120px; display: flex; align-items: center; overflow: hidden">
          <img-show
            :img-style="{ width: 'auto', height: 'auto' }"
            :src="basicInfo.pic"
          />
        </div>
        <div style="display: flex; flex-direction: column; justify-content: space-between; padding: 20px">
          <div style="font-size: 16px; font-weight: bold">
            {{ basicInfo.name }}
          </div>
          <div>
            <span style="padding-right: 20px;">规格类型: {{ basicInfo.specModel || '--' }}</span>
            <span style="padding-right: 20px;">限时折扣: {{ basicInfo.discountName || '--' }}</span>
            <span>会员专享: {{ basicInfo.memberDiscountName || '--' }}</span>
          </div>
        </div>
      </div>

      <div
        class="search-bar"
      >
        <el-form
          ref="searchFormRef"
          :inline="true"
          class="search-form"
          :model="searchForm"
          label-width="auto"
          @submit.prevent
        >
          <!-- 表单项 -->
          <div class="input-row">
            <el-form-item
              prop="partyCode"
              label="商品编码:"
            >
              <el-input
                v-model="searchForm.partyCode"
                type="text"
                clearable
                placeholder="商品编码"
              />
            </el-form-item>

            <template
              v-for="(item, index) in columns"
              :key="index"
            >
              <el-form-item
                :prop="item.key"
                :label="item.key + ':'"
              >
                <el-input
                  v-model="searchForm[item.key]"
                  type="text"
                  clearable
                  :placeholder="item.key"
                />
              </el-form-item>
            </template>

            <el-form-item>
              <div
                class="default-btn primary-btn"
                @click="onSearch(true)"
              >
                {{ $t('crud.searchBtn') }}
              </div>
              <div
                class="default-btn"
                @click="onResetSearch"
              >
                重置
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 操作按钮 -->
      <div class="operation-bar">
        <el-checkbox
          v-model="selectAll"
          :disabled="dataList.length===0"
          class="all-check-btn"
          @change="onSelectAll"
        >
          {{ $t('publics.selectAll') }}
        </el-checkbox>
        <span
          v-if="dataListSelections.length"
          class="had-selected"
        >已选 {{ dataListSelections.length }}</span>
        <div
          class="default-btn primary-btn"
          @click="onSetBatch()"
        >
          批量设置
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con prod-table">
        <el-table
          ref="prodListTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @selection-change="onSelectSome"
        >
          <el-table-column
            type="selection"
            width="55"
          />

          <el-table-column
            fixed
            prop="partyCode"
            label="商品编码"
            show-overflow-tooltip
            min-width="150"
          />

          <template
            v-for="(item, index) in columns"
            :key="index"
          >
            <el-table-column
              :prop="item.key"
              :label="item.key"
              min-width="100"
            />
          </template>

          <el-table-column
            prop="buyingPrice"
            label="进货价"
            :width="100"
          />

          <el-table-column
            prop="tradeTerm"
            label="交期"
            :width="100"
          >
            <template #default="scope">
              {{ scope.row.tradeTerm ? scope.row.tradeTerm > 1 ? `${scope.row.tradeTerm}日发货` : '当日发货' : '--' }}
            </template>
          </el-table-column>

          <el-table-column
            prop="stocks"
            label="库存"
            :width="100"
          >
            <template #default="scope">
              {{ scope.row.stocks || '--' }}
            </template>
          </el-table-column>

          <el-table-column
            prop="floorPrice"
            label="底价"
            :width="100"
          />

          <el-table-column
            prop="oriPrice"
            label="面价"
            :width="100"
          />

          <el-table-column
            prop="price"
            label="销售价"
            :width="100"
          />

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="300"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onSet([scope.row])"
                >
                  价格
                </div>
                <div
                  class="default-btn text-btn"
                  @click="onChannel(scope.row)"
                >
                  渠道信息
                </div>
                <div
                  class="default-btn text-btn"
                  @click="onViewPrice(scope.row)"
                >
                  查看折后价
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <el-dialog
      v-model="visible"
      :width="400"
      :close-on-click-modal="false"
      title="价格"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        :label-width="100"
        @submit.prevent
      >
        <el-form-item
          prop="floorPrice"
          label="底价"
        >
          <el-input-number
            v-model="dataForm.floorPrice"
            :min="1"
            :max="99999999"
            :precision="0"
          />
        </el-form-item>

        <el-form-item
          prop="oriPrice"
          label="面价"
        >
          <el-input-number
            v-model="dataForm.oriPrice"
            :min="0"
            :max="99999999"
          />
        </el-form-item>

        <el-form-item
          prop="price"
          label="销售价"
        >
          <el-input-number
            v-model="dataForm.price"
            :min="0"
            :max="99999999"
            :precision="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <div
            class="default-btn"
            @click="visible = false"
          >
            取消
          </div>
          <div
            class="default-btn primary-btn"
            @click="onSubmitSet()"
          >
            {{ $t("shopProcess.confirm") }}
          </div>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="visiblePrice"
      :width="500"
      title="查看折后价"
    >
      <el-form
        ref="dataPriceFormRef"
        :model="dataPriceForm"
        :label-width="150"
      >
        <el-form-item
          prop="oriPrice"
          label="数量"
        >
          <el-input-number
            v-model="dataPriceForm.count"
            :min="0"
            :max="99999999"
            @change="onGetPrice"
          />
        </el-form-item>

        <el-form-item
          prop="oriPrice"
          label="全网买会员等级"
        >
          <el-select
            v-model="dataPriceForm.level"
            @change="onGetPrice"
          >
            <el-option
              v-for="n in 10"
              :key="n"
              :value="n"
              :label="'VIP' + n"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="oriPrice"
          label="面价"
        >
          {{ dataPriceForm.oriPrice }}
        </el-form-item>

        <el-form-item
          prop="oriPrice"
          label="限时折扣"
        >
          <span style="word-break: break-all">{{ dataPriceForm.discountName }}</span>
        </el-form-item>

        <!-- <el-form-item
          prop="oriPrice"
          label="一刀云类目折扣"
        >
          {{ dataPriceForm.categoryDiscount }}
        </el-form-item> -->

        <el-form-item
          prop="oriPrice"
          label="会员专享折扣"
        >
          {{ dataPriceForm.memberDiscount }}
        </el-form-item>

        <el-form-item
          prop="oriPrice"
          label="折后单价"
        >
          {{ dataPriceForm.skuPrice }}
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      v-model="visibleChannel"
      :width="800"
      :close-on-click-modal="false"
      title="渠道信息"
    >
      <div>
        <div>
          商品编码: {{ channelForm.partyCode }}
        </div>
        <div style="margin: 10px 0;">
          <div
            class="default-btn primary-btn"
            @click="onAddChannel()"
          >
            添加
          </div>
        </div>
        <el-table
          :data="dataChannelList"
          header-cell-class-name="table-header"
          style="width: 100%"
        >
          <el-table-column
            prop="channelMerchantId"
            label="渠道商"
          >
            <template #default="scope">
              <el-radio
                v-model="selChannelId"
                :label="scope.row.channelMerchantId"
                @change="selChannelId = scope.row.channelMerchantId"
              >
                {{ channelList.find(d => d.id == scope.row.channelMerchantId)?.channelMerchantName }}
              </el-radio>
            </template>
          </el-table-column>

          <el-table-column
            prop="buyingPrice"
            label="进货价"
            :width="100"
          />

          <el-table-column
            prop="tradeTerm"
            label="交期"
            :width="100"
          >
            <template #default="scope">
              {{ scope.row.tradeTerm ? scope.row.tradeTerm > 1 ? `${scope.row.tradeTerm}日发货` : '当日发货' : '--' }}
            </template>
          </el-table-column>

          <el-table-column
            prop="stocks"
            label="库存"
            :width="100"
          >
            <template #default="scope">
              {{ scope.row.stocks || '--' }}
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="150"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onEditChannel(scope.row)"
                >
                  编辑
                </div>
                <div
                  class="default-btn text-btn"
                  @click="onDelChannel(scope.$index)"
                >
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div>
          <div
            class="default-btn"
            @click="visibleChannel = false"
          >
            取消
          </div>
          <div
            class="default-btn primary-btn"
            @click="onSubmitChannel()"
          >
            {{ $t("shopProcess.confirm") }}
          </div>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="visibleAddChannel"
      :width="400"
      :close-on-click-modal="false"
      :title="`${ channelType == 'add' ? '新增' : '编辑' }渠道商信息`"
    >
      <el-form
        ref="channelFormRef"
        :model="dataChannelForm"
        :rules="dataRule"
        :label-width="100"
        @submit.prevent
      >
        <el-form-item
          prop="channelMerchantId"
          label="渠道商"
        >
          <el-select
            v-model="dataChannelForm.channelMerchantId"
            placeholder="请选择"
            clearable
            :disabled="channelType == 'edit'"
          >
            <el-option
              v-for="item in channelList"
              :key="item.id"
              :label="item.channelMerchantName"
              :value="item.id"
              :disabled="addedList.includes(item.id)"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="buyingPrice"
          label="进货价"
        >
          <el-input-number
            v-model="dataChannelForm.buyingPrice"
            :min="1"
            :max="999"
            :precision="0"
          />
        </el-form-item>

        <el-form-item
          prop="tradeTerm"
          label="交期"
        >
          <el-input-number
            v-model="dataChannelForm.tradeTerm"
            :min="0"
            :max="99999999"
          />
        </el-form-item>

        <el-form-item
          prop="stocks"
          label="库存"
        >
          <el-input-number
            v-model="dataChannelForm.stocks"
            :min="0"
            :max="99999999"
            :precision="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <div
            class="default-btn"
            @click="visibleAddChannel = false"
          >
            取消
          </div>
          <div
            class="default-btn primary-btn"
            @click="onSubmitAddChannel()"
          >
            {{ $t("shopProcess.confirm") }}
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'

const props = defineProps({
  id: {
    default: null,
    type: Number
  }
})

const visible = ref(false)
const visiblePrice = ref(false)
const visibleChannel = ref(false)
const visibleAddChannel = ref(false)

let tempSearchForm = null // 保存上次点击查询的请求条件
let theParams = null // 保存上次点击查询的请求条件

const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({})

const dataForm = ref({})
const dataRule = ref({
  floorPrice: [{ required: true, message: '低价不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '销售价不能为空', trigger: 'blur' }],
  oriPrice: [{ required: true, message: '面价不能为空', trigger: 'blur' }],
  channelMerchantId: [{ required: true, message: '渠道商不能为空', trigger: 'blur' }],
  buyingPrice: [{ required: true, message: '进货价不能为空', trigger: 'blur' }],
  tradeTerm: [{ required: true, message: '交期不能为空', trigger: 'blur' }],
  stocks: [{ required: true, message: '库存不能为空', trigger: 'blur' }]
})

const dataPriceForm = ref({})

let prodId = null
let shopId = null
const route = useRoute()
onMounted(() => {
  init()
})

const init = () => {
  prodId = route.query.prodId || props.id || null
  shopId = route.query.shopId || props.shopId || null
  getBasicInfo()
  getDataList(page)
  getChannelList()
}

const channelList = ref([])
const getChannelList = () => {
  http({
    url: http.adornUrl('/shop/channelMerchant/getListByCond'),
    method: 'get',
    params: http.adornParams({})
  }).then(res => {
    channelList.value = res.data
  })
}

const router = useRouter()
const onBack = () => {
  const { page, search } = route.query
  router.replace({
    path: '/prod/prod-list/index',
    query: { page, search }
  })
}

const basicInfo = ref({})
const properties = ref('')
const columns = computed(() => {
  if (properties.value) {
    const clos = []
    const _cols = properties.value.split(';')
    _cols.forEach(d => {
      clos.push({
        key: d.split(':')[0]
      })
    })
    return clos
  }
  return []
})

const getBasicInfo = () => {
  http({
    url: http.adornUrl('/platform/sku/getDiscountInfoByProdId'),
    method: 'get',
    params: http.adornParams({
      prodId,
      shopId
    })
  }).then(res => {
    basicInfo.value = res.data || {}
  })
}

const getDataList = (pageParam, newData = false) => {
  if (page) {
    const size = Math.ceil(page.total / page.pageSize)
    page.currentPage = (page.currentPage > size ? size : page.currentPage) || 1
  }
  if (newData || !tempSearchForm) {
    theParams = {
      propertiesStr: getSearchStr()
    }
    tempSearchForm = {
      current: pageParam == null ? page.currentPage : pageParam.currentPage,
      size: pageParam == null ? page.pageSize : pageParam.pageSize,
      prodId: prodId || null,
      shopId: shopId || null,
      partyCode: searchForm.partyCode || null
    }
  } else {
    tempSearchForm.current = pageParam == null ? page.currentPage : pageParam.currentPage
    tempSearchForm.size = pageParam == null ? page.pageSize : pageParam.pageSize
  }
  http({
    url: http.adornUrl('/platform/sku/pageSku'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        tempSearchForm,
        theParams
      )
    )
  }).then(({ data }) => {
    dataList.value = (data.records || []).map(d => {
      const fields = (d.properties || '').split(';')
      fields.forEach(_d => {
        const _kv = _d.split(':')
        d[_kv[0]] = _kv[1]
      })
      return d
    })
    if (data.records.length) {
      properties.value = data.records[0].properties
    }
    page.total = data.total
    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.currentPage > 1) {
      page.currentPage = 1
      getDataList()
    }
  })
}

const getSearchStr = () => {
  const ret = []
  for (const k in searchForm) {
    if (searchForm[k] && k != 'partyCode') {
      const str = `${k}:${searchForm[k]}`
      ret.push(str)
    }
  }
  return ret.join(';')
}

// 条件查询
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

// 多选变化
const dataListSelections = ref([])
const selectAll = ref(false) // 是否全选
const onSelectSome = (val) => {
  dataListSelections.value = val
  selectAll.value = val.length === dataList.value.length
  if (dataList.value.length === 0) {
    selectAll.value = false
  }
}

const onSet = (rows) => {
  visible.value = true
  nextTick(() => {
    dataFormRef.value.resetFields()
    if (rows.length == 1) {
      dataForm.value = {
        skuIds: [rows[0].skuId],
        oriPrice: rows[0].oriPrice,
        price: rows[0].price,
        floorPrice: rows[0].floorPrice
      }
    } else {
      const skuIds = rows.map(d => d.skuId)
      dataForm.value = {
        skuIds,
        oriPrice: '',
        price: '',
        floorPrice: ''
      }
    }
  })
}

const onSetBatch = () => {
  if (!dataListSelections.value.length) {
    ElMessage({
      message: '请选择记录',
      type: 'warning',
      duration: 1500
    })
    return
  }
  onSet(dataListSelections.value)
}

const dataFormRef = ref(null)
const onSubmitSet = () => {
  dataFormRef.value?.validate((v) => {
    if (v) {
      const { skuIds, oriPrice, price, floorPrice } = dataForm.value
      const postData = []
      skuIds.forEach(d => {
        postData.push({
          prodId,
          skuId: d,
          oriPrice,
          price,
          floorPrice
        })
      })
      http({
        url: http.adornUrl('/platform/sku'),
        method: 'put',
        data: postData
      }).then(res => {
        getDataList()
        visible.value = false
      })
    }
  })
}

const onViewPrice = ({ skuId }) => {
  visiblePrice.value = true
  dataPriceForm.value = {}
  dataPriceForm.value.skuId = skuId
}

const onGetPrice = () => {
  const { count, level } = dataPriceForm.value
  if (count && level) {
    http({
      url: http.adornUrl('/platform/sku/getSkuPrice'),
      method: 'post',
      data: http.adornData({
        ...dataPriceForm.value,
        shopId
      })
    }).then(res => {
      dataPriceForm.value = {
        ...res.data,
        count,
        level
      }
    })
  }
}

const dataChannelList = ref([])
const channelForm = ref({})
const selChannelId = ref('')
const onChannel = (row) => {
  visibleChannel.value = true
  nextTick(() => {
    channelForm.value = row
    if (row.channelMerchantConfig) {
      const _data = JSON.parse(row.channelMerchantConfig)
      dataChannelList.value = _data.channelMerchants || []
      selChannelId.value = _data.channelMerchantId
    } else {
      dataChannelList.value = []
      selChannelId.value = ''
    }
  })
}

const onSubmitChannel = () => {
  if (dataChannelList.value.length == 0) {
    ElMessage.warning('请添加渠道商')
    return
  }
  if (!dataChannelList.value.find(d => d.channelMerchantId == selChannelId.value)) {
    ElMessage.warning('请选择渠道商')
    return
  }
  const json = JSON.stringify({
    channelMerchants: dataChannelList.value,
    channelMerchantId: selChannelId.value
  })
  const postData = [
    {
      prodId,
      skuId: channelForm.value.skuId,
      channelMerchantConfig: json
    }
  ]
  http({
    url: http.adornUrl('/platform/sku'),
    method: 'put',
    data: postData
  }).then(res => {
    getDataList()
    visibleChannel.value = false
  })
}

const addedList = ref([])
const dataChannelForm = ref({})
const channelType = ref('add')
const onAddChannel = () => {
  visibleAddChannel.value = true
  channelType.value = 'add'
  nextTick(() => {
    channelFormRef.value.resetFields()
    dataChannelForm.value = {}
    addedList.value = dataChannelList.value.map(d => d.channelMerchantId)
  })
}

const onEditChannel = (row) => {
  visibleAddChannel.value = true
  channelType.value = 'edit'
  nextTick(() => {
    channelFormRef.value.resetFields()
    dataChannelForm.value = {
      ...row
    }
  })
}

const onDelChannel = (index) => {
  dataChannelList.value.splice(index, 1)
}

const channelFormRef = ref(null)
const onSubmitAddChannel = () => {
  channelFormRef.value?.validate((v) => {
    if (!v) return
    const index = dataChannelList.value.findIndex(d => d.channelMerchantId == dataChannelForm.value.channelMerchantId)
    if (channelType.value == 'add') {
      if (index > -1) {
        ElMessage.warning('渠道商已存在')
        return
      }
      dataChannelList.value.push({
        ...dataChannelForm.value
      })
    } else {
      dataChannelList.value.splice(index, 1, {
        ...dataChannelForm.value
      })
    }
    visibleAddChannel.value = false
  })
}

// 全选按钮
const prodListTableRef = ref(null)
const onSelectAll = () => {
  prodListTableRef.value?.toggleAllSelection()
}

/**
 * 重置表单
 * @param {String} formName 表单名称
 */
const searchFormRef = ref(null)
const onResetSearch = () => {
  searchFormRef.value.resetFields()
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.main-container {
  .table-con .table-cell-con .table-cell-text{
    word-break: break-all
  }
  .operation-bar {
    position: relative;
    .all-check-btn {
      margin-right: 10px;
    }
    .had-selected {
      font-size: 12px;
      margin-right: 10px;
    }
  }

  .tag-text {
    display: inline-block;
    font-size: 12px;
    padding: 3px 5px;
    border-radius: 3px;
    color: #fff;
    cursor: pointer
  }
}
:deep(.export-load) {
  top: -50% !important;
}
</style>
